from apps.common.base.dao import BaseDao
from apps.system.admin.serializers import *
from apps.account.serializers import Token
from apps.account.dao import AccountDao
from apps.common.utils.tools import random_str, random_uuid
from apps.common.extension.customException import VerifyException

class AdminDao(BaseDao):
    MODEL_CLASS = Admin
    SERI_CLASS = AdminBaseSerializer

    def findAllAdmin(self):
        _list = AdminDao().findAll().filter(role__types='admin').select_related('role', 'account', 'lessee')
        return _list
    def findAllAdminByLessee(self, lessee):
        _list = self.getAllAdmin(self).filter(lessee=lessee)
        return _list
    

    def replaceToken(self, userId):

        old_token = Token.objects.filter(user_id=userId)
        old_token.delete()
        token = Token.objects.create(user_id=userId)

        return token
    
    def createAdmin(self, params):
        if not params.get('lessee'):
            raise VerifyException('lessee参数必填')
        if not params.get('role'):
            raise VerifyException('role参数必填')
        data = {
            'lessee': params.get('lessee'),
            'password': params.get('password') or '',
        }
        if params.get('username'):
            accounts = AccountDao().findAll().filter(username=params.get('username'))
            if accounts.exists():
                raise VerifyException('用户名已存在')
            data['username'] = params.get('username')
        else:
            data['username'] = random_uuid()
        
        account = AccountDao().create(data)
        data = {}
        data['lessee'] = params.get('lessee')
        data['account'] = account.id
        data['role'] = params.get('role')
        data['phone'] = params.get('phone')
        data['nickname'] = params.get('nickname')
        data['realname'] = params.get('realname')
        data['status'] = params.get('status')
        data['checkStatus'] = params.get('checkStatus') or 'PASS'
        _admin = AdminDao().create(data)
        if _admin:
            if not params.get('username'):
                username = 10100000 + account.id
                account = AccountDao().update(_admin.account.id, {'username': username})

            nickname = _admin.nickname or account.username
            AdminDao().update(_admin.id, {'nickname': nickname})
